const app = getApp();
var md5Util = require('../utils/md5.js')
var serverPath = "https://api.iaisong.com";
// var serverPath ='http://192.168.2.110:8088';
function request(opt) {
  var sessionKey = wx.getStorageSync("token")
  var timestamp = Date.parse(new Date());
  timestamp = timestamp / 1000;
  var signStr = "appKey" + app.appKey + "sessionKey"+sessionKey+"timestamp" + timestamp + "signMethod" + app.signMethod + "version" + app.version;
  wx.showNavigationBarLoading();
  wx.request({
    method:opt.method || 'GET',
    header:{
      'content-type': 'application/json' // 默认值
    },
    dataType:'json',
    url:serverPath + opt.url,
    data:{
      appKey:app.appKey,
      sessionKey:sessionKey || '',
      signMethod:app.signMethod,
      timestamp:timestamp,
      version:app.version,
      sign:md5Util.hexMD5(app.secretKey + signStr),
      data:opt.data
    },
    success: function (res) {
      if (res.statusCode == 200) {
        if (res.data.code == 0) {
          if (opt.success) {
            console.log(res)
            opt.success(res);
          }
        } else if (res.data.code == 5004) {
          console.log("remove invalid token")
          wx.removeStorageSync("token")
          login();
        } else {
          console.warn(res.data);
          wx.showModal({
            content: res.data.msg,
            showCancel: false
          })
        }
      } else {
        console.error(res);
        wx.showModal({
          title: '微信异常',
          content: res.statusCode,
          showCancel: false
        })
      }
    },
    fail: function () {
      wx.showToast({
        icon: 'none',
        title: '远程连接失败',
      })
    },
    complete: function () {
      wx.hideNavigationBarLoading();
      wx.hideLoading()
    }
  })
}

function login() {
  wx.reLaunch({
    url: '/pages/index/index',
  })
}

module.exports = {
  serverPath: serverPath,
  request: request,
}